package com.zhugang.week13.dp;

/**
 * @program algorithms
 * @description: minPathSum
 * @author: chanzhugang
 * @create: 2022/09/13 00:28
 */
public class MinPathSum {

    /**
     * 64 最小路径和
     * https://leetcode.cn/problems/minimum-path-sum/
     *
     * @param grid
     * @return
     */
    public int minPathSum(int[][] grid) {
        /**
         * 最值问题：第一时间肯定想到dp， 定义状态、找状态转移方程
         */
        // dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid(i, j)

        int m = grid.length;
        int n = grid[0].length;

        int[][] dp = new int[m][n];

        int sum = 0;
        // 初始化第一行值
        for (int i = 0; i < m; i++) {
            sum += grid[i][0];
            dp[i][0] = sum;
        }

        sum = 0;
        // 初始化第一列值
        for (int j = 0; j < n; j++) {
            sum += grid[0][j];
            dp[0][j] = sum;
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                // 状态转移方程
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }

        return dp[m - 1][n - 1];
    }
}